import { files }  from '../db/models.js'
import {docEmbedding} from './index.js'

export const messageQueue = []
files.find({status: 'queuing'}).then(files => files.forEach(file => messageQueue.push(file)))
let isProcessing = false;
export function addToQueue(message) {
  messageQueue.push(message);
}
export async function handleQueue() {
  while (true) {
    if (messageQueue.length > 0 && !isProcessing) {
      isProcessing = true;
      const message = messageQueue[0];
      const fileInfo = await files.findOne({ name: message.name });
      if (fileInfo) {
        try {
          await processMessage(fileInfo);
        } catch (error) {
          console.error(`Error processing file: ${message.name}, error is ${error}`);
          await files.updateOne({ _id: fileInfo._id }, { $set: { status: 'error' } });
        } finally {
          messageQueue.shift();
          isProcessing = false;
        }
      } else {
        console.error(`File not found in the database: ${message.name}`);
        messageQueue.shift();
        isProcessing = false;
      }
    }
    await sleep(1000);
  }
}
function sleep(time){
  return new Promise((resolve) => setTimeout(resolve, time));
}
async function processMessage(fileInfo) {
  messageQueue[0].status = 'embedding'
  await docEmbedding(fileInfo)
  await files.updateOne({ _id: fileInfo._id }, { $set: { status: 'embedded' } });
}
